'use strict';

module.exports = {
  up: async (queryInterface, Sequelize) => {
    const now = new Date();
    
    // 首先查找或创建文件管理父菜单
    const [fileManagementMenu] = await queryInterface.sequelize.query(
      `SELECT id FROM menus WHERE path = '/files' AND type = 'menu' LIMIT 1`
    );

    let fileManagementId;
    if (fileManagementMenu.length > 0) {
      fileManagementId = fileManagementMenu[0].id;
      
      // 更新父菜单
      await queryInterface.sequelize.query(`
        UPDATE menus 
        SET 
          name = '文件管理',
          title = '文件管理',
          icon = 'solar:folder-linear',
          order_num = 800,
          visible = true,
          updated_at = ?
        WHERE id = ?
      `, {
        replacements: [now, fileManagementId]
      });
    } else {
      // 创建父菜单
      const uuid = require('uuid').v4();
      fileManagementId = uuid;
      
      await queryInterface.bulkInsert('menus', [{
        id: fileManagementId,
        parent_id: null,
        name: '文件管理',
        title: '文件管理',
        path: '/files',
        component: null,
        type: 'directory',
        icon: 'solar:folder-linear',
        order_num: 800,
        visible: true,
        status: true,
        cache: false,
        permission: null,
        redirect: '/files/list',
        created_at: now,
        updated_at: now,
      }]);
    }

    // 删除旧的单个文件管理菜单（如果存在）
    await queryInterface.sequelize.query(`
      DELETE FROM menus 
      WHERE path = '/files' AND parent_id IS NULL AND type != 'menu'
    `);

    // 检查子菜单是否已存在
    const [existingSubMenus] = await queryInterface.sequelize.query(
      `SELECT path FROM menus WHERE parent_id = ?`,
      { replacements: [fileManagementId] }
    );

    const existingPaths = existingSubMenus.map(menu => menu.path);

    // 准备要插入的子菜单
    const subMenus = [
      {
        id: require('uuid').v4(),
        parent_id: fileManagementId,
        name: '文件列表',
        title: '文件列表',
        path: '/files/list',
        component: '/File/index',
        type: 'menu',
        icon: 'solar:document-linear',
        order_num: 801,
        visible: true,
        status: true,
        cache: false,
        permission: 'file:read',
        redirect: null,
        created_at: now,
        updated_at: now,
      },
      {
        id: require('uuid').v4(),
        parent_id: fileManagementId,
        name: 'OSS配置',
        title: 'OSS配置',
        path: '/files/config',
        component: '/FileConfig/index',
        type: 'menu',
        icon: 'solar:settings-linear',
        order_num: 802,
        visible: true,
        status: true,
        cache: false,
        permission: 'file:config',
        redirect: null,
        created_at: now,
        updated_at: now,
      },
    ];

    // 只插入不存在的菜单
    const menusToInsert = subMenus.filter(menu => !existingPaths.includes(menu.path));
    
    if (menusToInsert.length > 0) {
      await queryInterface.bulkInsert('menus', menusToInsert);
    }

    // 更新已存在的子菜单
    for (const menu of subMenus) {
      if (existingPaths.includes(menu.path)) {
        await queryInterface.sequelize.query(`
          UPDATE menus 
          SET 
            name = ?,
            title = ?,
            component = ?,
            icon = ?,
            order_num = ?,
            permission = ?,
            updated_at = ?
          WHERE path = ? AND parent_id = ?
        `, {
          replacements: [
            menu.name,
            menu.title,
            menu.component,
            menu.icon,
            menu.order_num,
            menu.permission,
            now,
            menu.path,
            fileManagementId
          ]
        });
      }
    }

    console.log('文件管理菜单更新成功');
  },

  down: async (queryInterface, Sequelize) => {
    // 删除文件管理相关菜单
    await queryInterface.sequelize.query(`
      DELETE FROM menus WHERE path LIKE '/files%'
    `);
  },
};

